package driver.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;

//通用工具类
public class Util {

    //    日志调试开关
    public static boolean DEBUG = false;
    //    测试数据,发布版本的时候此变量一定要调整为false
    public static boolean DEBUG_DATE = false;

    //    根据不同级别打印不同日志
    public static void debugApp(char level, String message) {
        if (!DEBUG) return;
        switch (level) {
            case 'd':
                Log.d("hwj", message);
                break;
            case 'e':
                Log.e("hwj", message);
                break;
        }
    }

    //    获得json字符中指定的key的值
    public static String getJsonKeyValue(String key, String response) {
        try {
            JSONObject object = new JSONObject(response);
            String value = object.get(key).toString();
            return value;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    //    保存json内容到hashMap中
    public static HashMap<String, String> parseResponse(String json) {
        try {
            HashMap<String, String> actionMap = new HashMap<String, String>();
            JSONObject actionObject = (new JSONObject(json));
            Iterator iterator = actionObject.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String value = actionObject.getString(key);
                actionMap.put(key, value);
            }
            return actionMap;
        } catch (JSONException e) {
            Log.d("hwj", "parseResponse异常 " + e.toString());
            e.printStackTrace();
        }
        return null;
    }

    public static void printMapContent(HashMap<String, String> map) {
        for (String o : map.keySet()) {
            Log.d("hwj", "key=" + o + " value=" + map.get(o));
        }
    }

    //    将日期和时间进行转换,只获得时间部分 具体的数据如示例 2021-1-02 19:55:00
    public static String parseDateToTime(String date) {
        int index = date.indexOf(" ");
        return date.substring(index, date.length());
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null != connectivity) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }
}

